/**
 *  操作实例
 */
import { ref, onBeforeMount, onUnmounted } from "vue";

export function useAction(apiFn, cb) {
    const timer = ref(null);
    const currentInstance = ref([]) // 当前的实例列表
    const newInstance = ref([])  // 异步请求的实例列表

    // 轮询状态接口
    const getNewInstance = (actionsIdList) => {
        if (timer.value === null) {
            timer.value = setInterval(() => {
                getList(actionsIdList)
            }, 10000);
        }else {
         
        }
    };

    // 请求实例列表之后发现有操作态的实例，刷新接口
    function doFetch(actionsIdList) {
        if (!actionsIdList.length) {
            return
        }
        if (timer.value) {
            clearInterval(timer.value)
            timer.value = null
        }

        getNewInstance(actionsIdList)
    }

    //  请求状态列表 
    async function getList(actionsIdList) {
        currentInstance.value = actionsIdList // 保存一份请求之前的操作中的机器，后续比对长度刷新列表
        const res = await apiFn({ instanceId: actionsIdList })
        newInstance.value = res.data.list || []
        checkInstance()
    }

    // 如果有状态改变刷新列表接口
    const checkInstance = () => {
        // 判断轮询状态更新成功就去刷列表，如果还有未成功的继续刷异步请求
        if (currentInstance.length != newInstance.value.length) {
            clearInterval(timer.value)
            timer.value = null
            cb(newInstance.value)  // 通知页面刷新列表,返回当前还没操作停止的数组
        } else {
            getNewInstance(currentInstance.value)
        }
    }

    // 用户操作了实例，停止定时器重新刷新接口
    function handleAction(actionsId) {
        if (!actionsId) {
            return
        }
        if (timer.value) {
            clearInterval(timer.value)
            timer.value = null
        }
        currentInstance.value.push(actionsId)

        getList(currentInstance.value)
    }

    onUnmounted(() => {
        timer.value && clearInterval(timer.value);
    });

    return {
        doFetch,
        handleAction
    };
}